// 引入编写好的api
const api = require('./api')
// 引入文件模块
const fs = require('fs')
// 引入处理路径的模块
const path = require('path')
// 引入处理post数据的模块
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
// 引入Express
const express = require('express')
const cors = require('cors')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
require('./../models')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(cookieParser())
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST'],
  alloweHeaders: ['Conten-Type', 'Authorization']
}))
app.use(api)
// 访问静态资源文件 这里是访问所有dist目录下的静态资源文件
app.use(express.static(path.resolve(__dirname, '../dist')))

var onlineUserList = []

var onlineUserCount = 0

var room = io.of('/room')
room.on('connection', function (socket) {
  console.log('新连接已创建 !')
  socket.on('login', function (obj) {
    socket.socketId = obj.id
    var sign = false
    for (let i = 0; i < onlineUserList.length; i++) {
      if (obj.id === onlineUserList[i].id) {
        sign = true
        break
      }
    }
    if (!sign) onlineUserList.push(obj)
    var clientIpAddress = socket.request.connection
    console.log(clientIpAddress)
    room.emit('login', {onlineUserList: onlineUserList, onlineUserCount: onlineUserCount, msgUser: obj})
    socket.emit('loginSuccess', {onlineUserList: onlineUserList, sign: 1})
    console.log(obj.username + '加入了群聊')
  })
  socket.on('disconnect', function () {
    console.log(socket.socketId)
    var exitObj = {}
    var sign = false
    for (var i = 0; i < onlineUserList.length; i++) {
      if (onlineUserList[i].id === socket.socketId) {
        onlineUserList[i].id = -1
        exitObj = onlineUserList[i]
        sign = true
        break
      }
    }
    var a = []
    if (sign) {
      for (let i = 0; i < onlineUserList.length; i++) {
        if (onlineUserList[i].id !== -1) {
          a.push(onlineUserList[i])
        }
      }
    }
    onlineUserList = a
    onlineUserCount--
    room.emit('logout', {onlineUserList: onlineUserList, onlineUserCount: onlineUserCount, msgUser: exitObj})
    console.log(exitObj)
    console.log(exitObj.username + '退群了')
  })
  socket.on('message', function (obj) {
    console.log(obj)
    obj.onlineUserList = onlineUserList
    room.emit('message', obj)
    console.log(obj.user.username + '说：' + obj.msg)
  })
})
// 监听8088端口
server.listen(8088)
console.log('success listen…………')
